package org.varscape.core.reader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import org.varscape.core.constants.InputFileType;


// This class handles all file type checks and calls the correct constructor.
public abstract class VariationFileReaderFactory {

	// all input types should have iterator reader
	public static IIteratorReader buildIteratorReader(String filePath) {
		InputFileType type = identifyReaderType(filePath);
		try {		
			switch (type) {
				case VCF:
					return new VCFIteratorReader(new BufferedInputStream(new FileInputStream(filePath)));
				case ZIPPED_VCF:
				case TABIX:
					return new VCFIteratorReader(new GZIPInputStream(new BufferedInputStream(new FileInputStream(filePath))));
				default: return null;
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}	

	// only Tabix has indexed reader
	public static IIndexedReader buildIndexedReader(String filePath) {
		InputFileType type = identifyReaderType(filePath);
		switch (type) {
			case VCF: return null;
			case ZIPPED_VCF: return null;
			case TABIX:  return new VCFIndexedReader(filePath);
			default: return null;
		}
	}
	
	// identify file type from file extension
	public static InputFileType identifyReaderType(String filePath) {
		// Is it case sensitive?
		if (filePath.endsWith(".vcf.gz")) {
			if ((new File(filePath+".tbi")).exists()) {
				return InputFileType.TABIX;
			} else {
				return InputFileType.ZIPPED_VCF;
			}
		} else if (filePath.endsWith(".vcf")) {
			return InputFileType.VCF;
		}
		return InputFileType.UNKNOWN;
	}
}
